package com.ruoyi.security.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.security.mapper.UserMapper;
import com.ruoyi.security.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

//package com.ruoyi.security.service;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.stereotype.Service;
//
///**
// * @author Administrator
// * @version 1.0
// **/
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    //根据 账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select(SysUser::getUserName, SysUser::getStatus);
//        queryWrapper.eq(SysUser::getUserName, username);
//        //将来连接数据库根据账号查询用户信息
//        SysUser user = userMapper.selectOne(queryWrapper);
        System.out.println("用户查询");
        System.out.println(username);
        SysUser user = userMapper.selectByUserName(username);
        if(user == null){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //将userDto转成json
        String[] strings = new String[0];
        String principal = JSON.toJSONString(user);
        UserDetails userDetails = User.withUsername(principal).password(user.getPassword()).authorities(strings).build();
        return userDetails;
    }
}
